﻿namespace Blaze.Framework.LuaExtensions
{
    using Pooling;
    using XLua;

    /// <summary>
    /// 用于延迟加载指定<see cref="LuaTable"/>中的<see cref="LuaFunction"/>。
    /// </summary>
    public class LazyLuaFunction : IPoolable
    {
        /// <summary>
        /// 获取加载好的<see cref="LuaFunction"/>，若未加载则加载。
        /// </summary>
        public LuaFunction Value
        {
            get
            {
                if (!mIsInitialized)
                    initialize();
                return mFunction;
            }
        }

        #region IPoolable Members

        /// <summary>
        /// 当从池中取出该对象时调用此方法。
        /// </summary>
        public void OnGet()
        {
        }

        /// <summary>
        /// 当将该对象存到池中调用此方法。
        /// </summary>
        public void OnPut()
        {
            mTable = null;
            mFunctionName = null;
            mFunction = null;
            mIsInitialized = false;
        }

        #endregion

        /// <summary>
        /// 指定需要延迟加载的方法。
        /// </summary>
        /// <param name="table">方法所在的Lua表</param>
        /// <param name="functionName">方法名</param>
        public LazyLuaFunction Setup(LuaTable table, string functionName)
        {
            mTable = table;
            mFunctionName = functionName;
            return this;
        }

        private void initialize()
        {
            mIsInitialized = true;
            mFunction = mTable.Get<LuaFunction>(mFunctionName);
        }

        private LuaTable mTable;
        private LuaFunction mFunction;
        private string mFunctionName;
        private bool mIsInitialized;
    }
}